//
//  HealthManager.swift
//  HSMainViewControllerHandler
//
//  Created by haisheng huang on 16/4/6.
//  Copyright © 2016年 haisheng huang. All rights reserved.
//

import Foundation
import HealthKit


@available(iOS 8.0, *)

class HealthManager: NSObject {
    
    
    let healthKitStore: HKHealthStore = HKHealthStore()
    
    
    /**
     * HealthKit 授权
     **/
    @available(iOS 8.0, *)
    func authorizeHealthKit(_ completion: ((_ success: Bool, _ error: NSError?) -> Void)?) {
        
        //1. Set the types you want to read from HK Store
//        let healthKitTypesToRead = NSSet(array:[
//            HKObjectType.characteristicTypeForIdentifier(HKCharacteristicTypeIdentifierDateOfBirth)!,
//            HKObjectType.characteristicTypeForIdentifier(HKCharacteristicTypeIdentifierBloodType)!,
//            HKObjectType.characteristicTypeForIdentifier(HKCharacteristicTypeIdentifierBiologicalSex)!,
//            HKObjectType.quantityTypeForIdentifier(HKQuantityTypeIdentifierBodyMass)!,
//            HKObjectType.quantityTypeForIdentifier(HKQuantityTypeIdentifierDistanceWalkingRunning)!,
//            HKObjectType.quantityTypeForIdentifier(HKQuantityTypeIdentifierStepCount)!,
//            HKObjectType.quantityTypeForIdentifier(HKQuantityTypeIdentifierHeight)!,
//            HKObjectType.workoutType()])
        
        let healthKitTypesToRead = NSSet(array:[
            HKObjectType.quantityType(forIdentifier: HKQuantityTypeIdentifier.distanceWalkingRunning)!,
            HKObjectType.quantityType(forIdentifier: HKQuantityTypeIdentifier.stepCount)!
            ])
        
        //2. Set the types you want to write to HK Store
//        let healthKitTypesToWrite = NSSet(array:[
//            HKObjectType.quantityTypeForIdentifier(HKQuantityTypeIdentifierBodyMassIndex)!,
//            HKObjectType.quantityTypeForIdentifier(HKQuantityTypeIdentifierActiveEnergyBurned)!,
//            HKObjectType.quantityTypeForIdentifier(HKQuantityTypeIdentifierDistanceWalkingRunning)!,
//            HKQuantityType.workoutType()
//            ])
        
        //3. If the store is not available (for instance, iPad) return an error and don't go on.
        if !HKHealthStore.isHealthDataAvailable() {
            
            let error = NSError(domain: "com.raywenderlich.tutorials.healthkit", code: 2, userInfo: [NSLocalizedDescriptionKey:"HealthKit is not available in this Device"])
            
            if completion != nil {
                completion?(false, error)
            }
            
            return;
        }
        
        //4. Request HealthKit authorization  healthKitTypesToWrite as? Set<HKSampleType>
        healthKitStore.requestAuthorization(toShare: nil, read: (healthKitTypesToRead as! Set<HKObjectType>), completion: { (success, error) in
            if completion != nil {
                completion?(success, error as NSError?)
            }
        })
        
    }
    
    /**
     * 读取特征信息
     **/
    @available(iOS 8.0, *)
    func readProfile() -> (age: Int?, biologicalsex:HKBiologicalSexObject?, bloodtype:HKBloodTypeObject?) {
        
        var age:Int?
        var biologicalSex:HKBiologicalSexObject?
        var bloodType:HKBloodTypeObject?
        
        // 1. Request birthday and calculate age
        do {
            
            let birthDay = try healthKitStore.dateOfBirth()
            let today = Date()
            let differenceComponents = (Calendar.current as NSCalendar).components(NSCalendar.Unit.year, from: birthDay, to: today, options: NSCalendar.Options(rawValue: 0) )
            age = differenceComponents.year
            
        } catch {
//            print("Error reading Birthday: \(error)")
        }
        
        // 2. Read biological sex
        do {
            biologicalSex = try healthKitStore.biologicalSex()
        } catch {
//            print("Error reading Biological Sex: \(error)")
        }
        
        // 3. Read blood type
        do {
            bloodType = try healthKitStore.bloodType()
        } catch {
//            print("Error reading Blood Type: \(error)")
        }
        
        // 4. Return the information read in a tuple
        return (age, biologicalSex, bloodType)
    }
    
    
    /**
     * 查询采样信息
     **/
    @available(iOS 8.0, *)
    func readMostRecentSample(_ sampleType:HKSampleType , completion: (([HKSample]?, NSError?) -> Void)?)
    {
       
        // 1. Build the Predicate
        //let past = NSDate.distantPast() as NSDate
//        let now = NSDate()
//        let dateFormatter = NSDateFormatter()
//        dateFormatter.dateFormat = "yyyy-MM-dd"
//        let dateString = dateFormatter.stringFromDate(now)
//        let past = dateFormatter.dateFromString(dateString)
        
        let dateFormatter: DateFormatter = DateFormatter()
        dateFormatter.timeZone = TimeZone.current
        dateFormatter.dateFormat = "yyyy-MM-dd"
//        let offsetTime: NSInteger = NSTimeZone.systemTimeZone().secondsFromGMT
        //.dateByAddingTimeInterval(Double(offsetTime))
        
        let yesterday:Date = Date.init(timeInterval: -24 * 60 * 60 * 2.0, since: Date())
        let yesterdayStr: String = dateFormatter.string(from: yesterday)
        //        print(yesterdayStr + " 00:00:00")
        dateFormatter.dateFormat = "yyyy-MM-dd HH:mm:ss"
        
        let startDate: Date = dateFormatter.date(from: yesterdayStr + " 00:00:01")!
        let endDate: Date = dateFormatter.date(from: yesterdayStr + " 22:59:59")!
        
        let mostRecentPredicate = HKQuery.predicateForSamples(withStart: startDate, end:endDate, options: HKQueryOptions())
        
        // 2. Build the sort descriptor to return the samples in descending order
        let sortDescriptor = NSSortDescriptor(key:HKSampleSortIdentifierStartDate, ascending: false)
        // 3. we want to limit the number of samples returned by the query to just 1 (the most recent)
        let limit = NSIntegerMax
        
        // 4. Build samples query
        let sampleQuery = HKSampleQuery(sampleType: sampleType, predicate: mostRecentPredicate, limit: limit, sortDescriptors: [sortDescriptor])
        { (sampleQuery, results, error ) -> Void in
            
            if error != nil {
                completion?(nil,error as NSError?)
                return;
            }
            
//            print("results:\(results)")
            
            // Get the first sample
            //let mostRecentSample = results!.first as? HKQuantitySample
            let mostRecentSample = results!
            
            // Execute the completion closure
            if completion != nil {
                completion?(mostRecentSample,nil)
            }
        }
        // 5. Execute the Query
        self.healthKitStore.execute(sampleQuery)
    }

}





